package com.czmh.etc.onlinepubsys.controller.cmg;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czmh.etc.common.core.utils.Sequence;
import com.czmh.etc.onlinepubsys.constants.cmg.BusinessType;
import com.czmh.etc.onlinepubsys.entity.mingchuang.ApplyInfo;
import com.czmh.etc.onlinepubsys.enums.cmg.ApiCodeEnum;
import com.czmh.etc.onlinepubsys.json.cmg.JSONResult;
import com.czmh.etc.onlinepubsys.jy.utils.PageUtils;
import com.czmh.etc.onlinepubsys.jy.utils.Query;
import com.czmh.etc.onlinepubsys.model.EtcAfterSaleLog;
import com.czmh.etc.onlinepubsys.model.EtcCancel;
import com.czmh.etc.onlinepubsys.model.EtcReplace;
import com.czmh.etc.onlinepubsys.request.cmg.*;
import com.czmh.etc.onlinepubsys.response.cmg.AfterSaleRecordListResponse;
import com.czmh.etc.onlinepubsys.response.cmg.AfterSaleRecordObject;
import com.czmh.etc.onlinepubsys.response.cmg.ApiResponseBase;
import com.czmh.etc.onlinepubsys.services.EtcAfterSaleDeviceService;
import com.czmh.etc.onlinepubsys.services.EtcAfterSaleLogService;
import com.czmh.etc.onlinepubsys.services.EtcCancelService;
import com.czmh.etc.onlinepubsys.services.EtcReplaceService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IEtcApplyService;
import com.czmh.etc.onlinepubsys.utils.DatetimeUtil;
import com.czmh.etc.onlinepubsys.utils.cmg.CmgHttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/{version}/api/cmg/ioapi/afterSale")
@Api(tags = "售后服务接口 - 招商局")
public class CmgAfterSaleController {
    @Value("${cmg.accessno}")
    private String accessno;

    @Autowired
    private IEtcApplyService etcApplyService;

    @Autowired
    private EtcCancelService etcCancelService;

    @Autowired
    private EtcAfterSaleDeviceService etcAfterSaleDeviceService;

    @Autowired
    private EtcReplaceService etcReplaceService;

    @Autowired
    private EtcAfterSaleLogService etcAfterSaleLogService;

    @PostMapping("/afterSaleCancel")
    @ApiOperation("售后取消接口-只支持业务类型1、换卡2、换签 4、卡签注销")
    public JSONResult afterSaleCancel(@RequestBody AfterSaleCancelRequest req) {
        JSONResult result = new JSONResult();
        log.info("QueryDeviceRequest:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.newpost(BusinessType.NEW_AFTER_SALE_CANCEL, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());

                //取消更换的时候同步更新更换记录表信息
                if (req.getBusinessType() == 1) {
                    if (r.bizContent != null) {
                        //检查售后设备表是否存在对应的设备信息
                        Map<String, Object> queryMap = new HashMap<>();
                        queryMap.put("deleteFlag", "0");
                        queryMap.put("type", "1");
                        queryMap.put("deviceSn", req.getEtcSn());
                        queryMap.put("orderId", req.getOrderId());
                        queryMap.put("activeStatus", "0");
                        List<EtcReplace> list = etcReplaceService.queryList(queryMap);
                        if (!CollectionUtils.isEmpty(list)) {
                            //更新售后设备表对应的设备激活信息
                            EtcReplace etcReplace = list.get(0);
                            etcReplace.setStatus(3);
                            etcReplace.setDeleteFlag(1);
                            etcReplaceService.update(etcReplace);
                        }
                    }
                }

                //取消更换的时候同步更新更换记录表信息
                if (req.getBusinessType() == 2) {
                    if (r.bizContent != null) {
                        //检查售后设备表是否存在对应的设备信息
                        Map<String, Object> queryMap = new HashMap<>();
                        queryMap.put("deleteFlag", "0");
                        queryMap.put("type", "2");
                        queryMap.put("deviceSn", req.getObuDeviceSn());
                        queryMap.put("orderId", req.getOrderId());
                        queryMap.put("activeStatus", "0");
                        List<EtcReplace> list = etcReplaceService.queryList(queryMap);
                        if (!CollectionUtils.isEmpty(list)) {
                            //更新售后设备表对应的设备激活信息
                            EtcReplace etcReplace = list.get(0);
                            etcReplace.setStatus(3);
                            etcReplace.setDeleteFlag(1);
                            etcReplaceService.update(etcReplace);
                        }
                    }
                }

                //取消卡签注销的时候同步更新记录表信息状态
                if (req.getBusinessType() == 4) {
                    if (r.bizContent != null) {
                        //检查售后设备表是否存在对应的设备信息
                        Map<String, Object> queryMap = new HashMap<>();
                        queryMap.put("deleteFlag", "0");
                        queryMap.put("type", "3");
                        queryMap.put("channelType", "0");
                        queryMap.put("orderId", req.getOrderNo());
                        queryMap.put("stateNotIn", "2");
                        List<EtcCancel> list = etcCancelService.queryList(queryMap);
                        if (!CollectionUtils.isEmpty(list)) {
                            //更新售后设备表对应的设备激活信息
                            EtcCancel etcCancel = list.get(0);
                            etcCancel.setState(2);
                            etcCancel.setDeleteFlag(1);
                            etcCancelService.update(etcCancel);
                        }
                    }
                }
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/queryDevice")
    @ApiOperation("查询设备状态")
    public JSONResult queryDevice(@RequestBody QueryDeviceRequest req) {
        JSONResult result = new JSONResult();
        log.info("QueryDeviceRequest:{}", JSON.toJSONString(req));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("obuSnState", 0);
        jsonObject.put("etcSnState", 0);
        //查询售后设备表ETC卡情况
        if (req.getType() == 1 || req.getType() == 3) {
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("deleteFlag", "0");
            queryMap.put("type", "1");
            queryMap.put("deviceSn", req.getEtcSn());
            queryMap.put("activeStatus", "0");
            int r = etcAfterSaleDeviceService.queryTotal(queryMap);
            if (r > 0) {
                jsonObject.put("etcSnState", 1);
            }
        }
        //查询售后设备表obu情况
        if (req.getType() == 2 || req.getType() == 3) {
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("deleteFlag", "0");
            queryMap.put("type", "2");
            queryMap.put("deviceSn", req.getEtcSn());
            queryMap.put("activeStatus", "0");
            int r = etcAfterSaleDeviceService.queryTotal(queryMap);
            if (r > 0) {
                jsonObject.put("obuSnState", 1);
            }
        }
        result.setRspData(jsonObject.toJSONString());
        return result;
    }


    @PostMapping("/cardLossOperation")
    @ApiOperation("卡片挂失/解挂接口")
    public JSONResult cardLossOperation(@RequestBody CardLossOperationRequest req) {
        JSONResult result = new JSONResult();
        log.info("cardLossOperation:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.newpost(BusinessType.NEW_CARD_LOSS_OPERATION, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            Date date = new Date();
            EtcCancel etcCancel = new EtcCancel();
            etcCancel.setDeleteFlag(0);
            etcCancel.setCreateTime(date);
            etcCancel.setUpdatedTime(date);
            etcCancel.setCreateUserId(req.getUserId());
            etcCancel.setReqData(JSON.toJSONString(req));
            etcCancel.setId(Sequence.getId());
            etcCancel.setOrderId(req.getOrderId());
            etcCancel.setState(4);
            etcCancel.setChannelType(1);
            etcCancel.setType(req.getBusinessType());
            etcCancel.setContent(req.getCardNo());
            etcCancel.setUserId(req.getUserId());
            etcCancel.setReason(req.getTel());
            etcCancel.setRemark(req.getRemark());
            etcCancelService.saveSelective(etcCancel);
//            if (r.bizContent != null) {
//                result.setRspData(r.getBizContent());
//                result.setMessage(r.getMsg());
//                result.setCurrentTime(r.getReceiveTime());
//
//                Date date = new Date();
//                EtcCancel etcCancel = new EtcCancel();
//                etcCancel.setDeleteFlag(0);
//                etcCancel.setCreateTime(date);
//                etcCancel.setUpdatedTime(date);
//                etcCancel.setCreateUserId(req.getUserId());
//                etcCancel.setReqData(JSON.toJSONString(req));
//                etcCancel.setId(Sequence.getId());
//                etcCancel.setOrderId(req.getOrderId());
//                etcCancel.setState(4);
//                etcCancel.setChannelType(1);
//                etcCancel.setType(req.getBusinessType());
//                etcCancel.setContent(req.getCardNo());
//                etcCancel.setUserId(req.getUserId());
//                etcCancel.setReason(req.getTel());
//                etcCancel.setRemark(req.getRemark());
//                etcCancelService.saveSelective(etcCancel);
//            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/cardObuCancel")
    @ApiOperation("卡签注销提交接口")
    public JSONResult cardObuCancel(@RequestBody CardObuCancelRequest req) {
        //把脱落激活数据入库，等待后台审核通过之后调用定时任务完成对应的操作
        JSONResult result = new JSONResult();
        log.info("cardObuCancel:{}", JSON.toJSONString(req));

        //检查订单设备是否激活
        QueryWrapper<ApplyInfo> infoQueryWrapper = new QueryWrapper();
        infoQueryWrapper.eq("orderNo", req.getOrderId());
        ApplyInfo applyInfo = etcApplyService.queryObject(infoQueryWrapper);
        if (applyInfo == null) {
            result.setCode(JSONResult.FAIL);
            result.setCurrentTime("" + System.currentTimeMillis());
            result.setMessage("设备不存在！");
            return result;
        }
        if (applyInfo != null && applyInfo.getState() == 2) {
            //判断之前是否提交过申请
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("deleteFlag", "0");
            queryMap.put("type", "3");
            queryMap.put("channelType", "0");
            queryMap.put("orderId", req.getOrderNo());
            queryMap.put("stateNotIn", "2");
            int c = etcCancelService.queryTotal(queryMap);
            if (c > 0) {
                result.setCode(JSONResult.FAIL);
                result.setCurrentTime("" + System.currentTimeMillis());
                result.setMessage("请不要重复提交注销申请！");
                return result;
            } else {
            }
        } else {
            result.setCode(JSONResult.FAIL);
            result.setCurrentTime("" + System.currentTimeMillis());
            result.setMessage("设备未激活！");
            return result;
        }

        //数据入库等待审核
        //保存注销数据提交后台待审核
        Date date = new Date();
        EtcCancel etcCancel = new EtcCancel();
        etcCancel.setDeleteFlag(0);
        etcCancel.setCreateTime(date);
        etcCancel.setUpdatedTime(date);
        etcCancel.setCreateUserId(req.getUserId());
        etcCancel.setReqData(JSON.toJSONString(req));
        etcCancel.setId(Sequence.getId());
        etcCancel.setOrderId(req.getOrderId());
        etcCancel.setState(0);
        etcCancel.setChannelType(0);
        etcCancel.setImages(req.getImages());
        etcCancel.setType(3);
        etcCancel.setUserId(req.getUserId());
        etcCancel.setRemark(req.getRemark());
        etcCancel.setContent(req.getObuId());
        int r = etcCancelService.saveSelective(etcCancel);
        if (r > 0) {
            result.setCode(JSONResult.SUCCESS);
            result.setCurrentTime("" + System.currentTimeMillis());
            result.setMessage("注销申请提交成功！");
        } else {
            etcCancelService.delete(etcCancel.getId());
            result.setCode(JSONResult.FAIL);
            result.setCurrentTime("" + System.currentTimeMillis());
            result.setMessage("注销申请提交失败！");
        }
        return result;

/*
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.CARD_OBU_CANCEL, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        }else{
            result.setCode(JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
 */
    }

    @PostMapping("/cardReplaceSubmit")
    @ApiOperation("卡片更换提交接口")
    public JSONResult cardReplaceSubmit(@RequestBody CardReplaceSubmitRequest req) {
        JSONResult result = new JSONResult();
        log.info("cardReplaceSubmit:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        Date current = new Date();

        req.setClientKey(accessno + time);
        req.setTime(time);
        EtcReplace etcReplace = new EtcReplace();
        ApiResponseBase r = CmgHttpUtil.newpost(BusinessType.NEW_OBU_REPLACE_SUBMIT, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
                //更换成功插入数据到etc设备更换记录表
                etcReplace.setId(Sequence.getId());
                etcReplace.setUserId(req.getUserId());
                etcReplace.setOrderId(req.getOrderId());
                etcReplace.setType(1);
                etcReplace.setDeviceSn(req.getEtcSn());
                etcReplace.setDeviceId(req.getEtcSn());
                etcReplace.setStatus(0);
                etcReplace.setDeleteFlag(0);
                etcReplace.setCreateTime(current);
                etcReplace.setJsondata(JSON.toJSONString(req));
                etcReplace.setUpdatedTime(current);
                etcReplace.setRemark(req.getRemark());
                etcReplace.setUpdatedUserId(req.getUserId());
                etcReplace.setCreateUserId(req.getUserId());
                etcReplaceService.save(etcReplace);
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
            //更换失败插入数据到etc设备更换记录表
            etcReplace.setId(Sequence.getId());
            etcReplace.setUserId(req.getUserId());
            etcReplace.setOrderId(req.getOrderId());
            etcReplace.setType(1);
            etcReplace.setDeviceSn(req.getEtcSn());
            etcReplace.setDeviceId(req.getEtcSn());
            etcReplace.setStatus(2);
            etcReplace.setDeleteFlag(1);
            etcReplace.setCreateTime(current);
            etcReplace.setJsondata(JSON.toJSONString(req));
            etcReplace.setUpdatedTime(current);
            etcReplace.setUpdatedUserId(req.getUserId());
            etcReplace.setCreateUserId(req.getUserId());
            etcReplaceService.save(etcReplace);
        }
        //卡片更换提交之后同步售后数据入库
        try {
            syncAfterSaleRecordList();
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("卡片更换提交之后同步售后数据入库出错:{}", e.getMessage());
        }
        return result;
    }

    @PostMapping("/getAfterSaleRecordDetail")
    @ApiOperation("ETC售后记录接口")
    public JSONResult getAfterSaleRecordDetail(@RequestBody GetAfterSaleRecordDetailRequest req) {
        JSONResult result = new JSONResult();
        log.info("getAfterSaleRecordDetail:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.GET_AFTER_SALE_RECORD_DETAIL, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/getAfterSaleRecordList")
    @ApiOperation("ETC售后记录列表接口")
    public JSONResult getAfterSaleRecordList(@RequestBody GetAfterSaleRecordListRequest req) {
        JSONResult result = new JSONResult();
        log.info("getAfterSaleRecordList:{}", JSON.toJSONString(req));
        if (StringUtils.isEmpty(req.getUserId())) {
            result.setCode(JSONResult.FAIL);
            result.setCurrentTime("" + System.currentTimeMillis());
            result.setMessage("用户userId不能为空！");
            return result;
        }
        QueryWrapper<ApplyInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", req.getUserId());
        List<ApplyInfo> applyInfos = etcApplyService.queryList(queryWrapper);
        List<String> vehiclePlatList = new ArrayList<>();
        vehiclePlatList.add("aaaaaaaa");
        List<String> vehiclePlats = applyInfos.stream().map(dto -> dto.getVehiclePlate()).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(vehiclePlats)) {
            vehiclePlatList.addAll(vehiclePlats);
        }
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("page", req.getPageNum());
        queryMap.put("vehiclePlates", StringUtils.join(vehiclePlatList, ","));
        queryMap.put("month", req.getMonth());
        queryMap.put("limit", req.getPageSize());
        queryMap.put("sidx", "create_time desc");
        Query query = new Query(queryMap);
        List<EtcAfterSaleLog> list = etcAfterSaleLogService.queryList(query);
        int total = etcAfterSaleLogService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(list, total, req.getPageNum(), req.getPageSize());
        result.setCode(com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.SUCCESS);
        result.setCurrentTime("" + System.currentTimeMillis());
        result.setRspData(JSON.toJSONString(pageUtil));
        return result;
    }

    @PostMapping("/syncAfterSaleRecords")
    @ApiOperation("同步ETC售后记录列表接口")
    public JSONResult syncAfterSaleRecords(@RequestBody GetAfterSaleRecordListRequest req) {
        JSONResult result = new JSONResult();
        Date currentDate = new Date();
        if (req.getMonth() == null) {
            req.setMonth(DatetimeUtil.formatDate(currentDate, "yyyy-MM"));
        }
        req.setPageNum(1);
        req.setPageSize(10);
        log.info("syncAfterSaleRecords:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        result.setCurrentTime("" + time);
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.GET_AFTER_SALE_RECORD_LIST, req);
        int count = 0;
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                AfterSaleRecordListResponse afterSaleRecordListResponse = JSON.parseObject(r.getBizContent(), AfterSaleRecordListResponse.class);
                while (afterSaleRecordListResponse != null && afterSaleRecordListResponse.getRecord() != null && afterSaleRecordListResponse.getPage().getTotalCount() >= (afterSaleRecordListResponse.getPage().getPageNum() - 1) * afterSaleRecordListResponse.getPage().getPageSize() + afterSaleRecordListResponse.getRecord().size()) {
                    List<AfterSaleRecordObject> afterSaleRecordObjects = afterSaleRecordListResponse.getRecord();
                    for (int i = 0; i < afterSaleRecordObjects.size(); i++) {
                        AfterSaleRecordObject afterSaleRecordObject = afterSaleRecordObjects.get(i);
                        //查询对应的订单号记录是否存在，不存在则入库
                        if (etcAfterSaleLogService.isExistOrderNo(afterSaleRecordObject.getOrderNo()) == 0) {
                            //数据入库
                            EtcAfterSaleLog etcAfterSaleLog = new EtcAfterSaleLog();
                            BeanUtils.copyProperties(afterSaleRecordObject, etcAfterSaleLog);
                            etcAfterSaleLog.setId(Sequence.getId());
                            etcAfterSaleLog.setType(0);
                            etcAfterSaleLog.setDeleteFlag(0);
                            etcAfterSaleLog.setCreateTime(currentDate);
                            etcAfterSaleLog.setUpdatedTime(currentDate);
                            etcAfterSaleLogService.save(etcAfterSaleLog);
                            count++;
                        }
                    }
                    Long currentTime = System.currentTimeMillis();
                    req.setPageNum(afterSaleRecordListResponse.getPage().getPageNum() + 1);
                    req.setClientKey(accessno + currentTime);
                    req.setTime(currentTime);
                    r = CmgHttpUtil.post(BusinessType.GET_AFTER_SALE_RECORD_LIST, req);
                    if (r.bizContent == null) {
                        break;
                    } else {
                        afterSaleRecordListResponse = JSON.parseObject(r.getBizContent(), AfterSaleRecordListResponse.class);
                    }
                }
            }
        }
        result.setMessage("同步更新" + count + "条数据");
        return result;
    }

    //同步ETC售后记录列表接口
    private void syncAfterSaleRecordList() {
        JSONResult result = new JSONResult();
        GetAfterSaleRecordListRequest req = new GetAfterSaleRecordListRequest();
        Date currentDate = new Date();
        if (req.getMonth() == null) {
            req.setMonth(DatetimeUtil.formatDate(currentDate, "yyyy-MM"));
        }
        req.setPageNum(1);
        req.setPageSize(10);
        log.info("getAfterSaleRecordList:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        result.setCurrentTime("" + time);
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.GET_AFTER_SALE_RECORD_LIST, req);

        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                AfterSaleRecordListResponse afterSaleRecordListResponse = JSON.parseObject(r.getBizContent(), AfterSaleRecordListResponse.class);
                while (afterSaleRecordListResponse != null && afterSaleRecordListResponse.getRecord() != null && afterSaleRecordListResponse.getPage().getTotalCount() >= (afterSaleRecordListResponse.getPage().getPageNum() - 1) * afterSaleRecordListResponse.getPage().getPageSize() + afterSaleRecordListResponse.getRecord().size()) {
                    List<AfterSaleRecordObject> afterSaleRecordObjects = afterSaleRecordListResponse.getRecord();
                    for (int i = 0; i < afterSaleRecordObjects.size(); i++) {
                        AfterSaleRecordObject afterSaleRecordObject = afterSaleRecordObjects.get(i);
                        //查询对应的订单号记录是否存在，不存在则入库
                        if (etcAfterSaleLogService.isExistOrderNo(afterSaleRecordObject.getOrderNo()) == 0) {
                            //数据入库
                            EtcAfterSaleLog etcAfterSaleLog = new EtcAfterSaleLog();
                            BeanUtils.copyProperties(afterSaleRecordObject, etcAfterSaleLog);
                            etcAfterSaleLog.setId(Sequence.getId());
                            etcAfterSaleLog.setType(0);
                            etcAfterSaleLog.setDeleteFlag(0);
                            etcAfterSaleLog.setCreateTime(currentDate);
                            etcAfterSaleLog.setUpdatedTime(currentDate);
                            etcAfterSaleLogService.save(etcAfterSaleLog);
                        }
                    }
                    Long currentTime = System.currentTimeMillis();
                    req.setPageNum(afterSaleRecordListResponse.getPage().getPageNum() + 1);
                    req.setClientKey(accessno + currentTime);
                    req.setTime(currentTime);
                    r = CmgHttpUtil.post(BusinessType.GET_AFTER_SALE_RECORD_LIST, req);
                    if (r.bizContent == null) {
                        break;
                    } else {
                        afterSaleRecordListResponse = JSON.parseObject(r.getBizContent(), AfterSaleRecordListResponse.class);
                    }
                }
            }
        }
    }

    @PostMapping("/afterSaleSendMsg")
    @ApiOperation("卡签售后验证码发送接口")
    public JSONResult afterSaleSendMsg(@RequestBody AfterSaleSendMsgRequest req) {
        JSONResult result = new JSONResult();
        log.info("afterSaleSendMsg:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.newpost(BusinessType.NEW_AFTER_SALE_SEND_MSG, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/obuReplaceSubmit")
    @ApiOperation("标签更换提交接口")
    public JSONResult obuReplaceSubmit(@RequestBody ObuReplaceSubmitRequest req) {
        JSONResult result = new JSONResult();
        log.info("obuReplaceSubmit:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();

        Date current = new Date();
        req.setClientKey(accessno + time);
        req.setTime(time);
        EtcReplace etcReplace = new EtcReplace();
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.OBU_REPLACE_SUBMIT, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
                //更换成功插入数据到etc设备更换记录表
                etcReplace.setId(Sequence.getId());
                etcReplace.setUserId(req.getUserId());
                etcReplace.setOrderId(req.getOrderId());
                etcReplace.setType(2);
                etcReplace.setDeviceSn(req.getObuDeviceSn());
                etcReplace.setDeviceId(req.getObuDeviceSn());
                etcReplace.setStatus(0);
                etcReplace.setDeleteFlag(0);
                etcReplace.setCreateTime(current);
                etcReplace.setJsondata(JSON.toJSONString(req));
                etcReplace.setUpdatedTime(current);
                etcReplace.setRemark(req.getRemark());
                etcReplace.setUpdatedUserId(req.getUserId());
                etcReplace.setCreateUserId(req.getUserId());
                etcReplaceService.save(etcReplace);
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
            //更换失败插入数据到etc设备更换记录表
            etcReplace.setId(Sequence.getId());
            etcReplace.setUserId(req.getUserId());
            etcReplace.setOrderId(req.getOrderId());
            etcReplace.setType(2);
            etcReplace.setDeviceSn(req.getObuDeviceSn());
            etcReplace.setDeviceId(req.getObuDeviceSn());
            etcReplace.setStatus(2);
            etcReplace.setDeleteFlag(1);
            etcReplace.setCreateTime(current);
            etcReplace.setJsondata(JSON.toJSONString(req));
            etcReplace.setUpdatedTime(current);
            etcReplace.setUpdatedUserId(req.getUserId());
            etcReplace.setCreateUserId(req.getUserId());
            etcReplaceService.save(etcReplace);
        }
        //标签更换提交之后同步售后数据入库
        try {
            syncAfterSaleRecordList();
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("标签更换提交之后同步售后数据入库出错:{}", e.getMessage());
        }
        return result;
    }

    @PostMapping("/queryCardObuInfo")
    @ApiOperation("查询卡签信息接口")
    public JSONResult queryCardObuInfo(@RequestBody QueryCardObuInfoRequest req) {
        JSONResult result = new JSONResult();
        log.info("queryCardObuInfo:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.newpost(BusinessType.NEW_QUERY_CARD_OBU_INFO, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/afterSaleVerifyMsg")
    @ApiOperation("卡签验证码校验接口")
    public JSONResult afterSaleVerifyMsg(@RequestBody AfterSaleVerifyMsgRequest req) {
        JSONResult result = new JSONResult();
        log.info("afterSaleVerifyMsg:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.newpost(BusinessType.NEW_AFTER_SALE_VERIFY_MSG, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }
}
